<template>
	<view class="login">
		<view class="header"
			:style="{'height': app.globalData.navHeight + 'px','padding-top': app.globalData.tabHeight + 'px'}">
			<view class="box" @click="back">
				<image class="icon" src="../../static/images/svg/back.svg" mode="aspectFill"></image>
			</view>
		</view>
		<view class="top" :style="{'height': app.globalData.navHeight * 2 + 720 + 'rpx' ,}">
			<image class="logo" src="../../static/images/login.svg" mode=""></image>
		<!-- 	<input class="item-input" type="text" placeholder="请输入账号" v-model="userForm.account"
				placeholder-style="color:#666;line-height: 64rpx;"></input>
			<input class="item-input" type="password" placeholder="请输入密码" v-model="userForm.password"
				placeholder-style="color:#666;line-height: 64rpx;" style="top: 880rpx;"></input> -->
		</view>
	<!-- 	<button type="default" class="btn flex_center wx-btn wrap content flex_center" @click="md">
			<div class="f_32 c_f ">登录</div>
		</button> -->
		<button v-if="wxLogin == true" type="default" class="btn flex_center wx-btn wrap content flex_center"
			@click="loginWx">
			<!-- <image src="../../static/images/wx.svg" class="wx_icon"></image> -->
			<div class="f_32 c_f ">快速授权登录</div>
		</button>
		<button v-if="wxPhone" class="btn flex_center wx-btn wrap content flex_center" open-type="getPhoneNumber"
			@getphonenumber="onGetPhoneNumber">
			<div class="f_32 c_f ">授权手机号</div>
		</button>
		<view class="flex_center dark big" @click="radio(radioType==0?1:0)">
			<image v-if="radioType == 0" class="radio" src="../../static/images/radio.svg" mode="">
			</image>
			<image v-if="radioType == 1" class="radio" src="../../static/images/radio_a.svg" mode="">
			</image>

			<view class="c_7 f_24">我已阅读并同意<text class="c_0" @click.stop="gopage('yhxy')">《用户协议》</text>和<text class="c_0"
					@click.stop="gopage('yszc')">《隐私政策》</text></view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app'
	import { getSignature, getPolicyBase64 } from "@/utils/oss";
	import config from "@/ossutil/config";
	const app = ref<any>(getApp())
	import { userLogin, UserDeatil, loginInfo, loginInfoD, isWxLogin, editUserInfo } from '@/utils/api/user.ts'
	const md = () => {
		if (!userForm.value.account || !userForm.value.password) {
			uni.showToast({
				title: '请输入账号和密码',
				icon:'none'
			})
			return;
		}else{
			if(userForm.value.account=="admin" && userForm.value.password=="HcWEB1020")
			loginInfoD().then(res => {
				uni.setStorageSync('tokenName', res.data.tokenName);
				uni.setStorageSync('tokenValue', res.data.tokenValue);
				uni.setStorageSync('type', 1)
				uni.switchTab({
					url: '/pages/index/index'
				})
			})
		}
		
		
	}
	const userForm = ref({
		account: '',
		password: ''
	})
	//返回
	const back = () => {
		uni.navigateBack()
	}
	const code = ref<string>()

	const gopage = (val) => {
		uni.navigateTo({
			url: `/pages/my/richtext?id=${val}`
		})

	}
	onLoad(() => {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				if (res.errMsg == "login:ok") {
					code.value = res.code;
					console.log(code.value, 'code');
				} else {
					uni.showToast({
						title: '系统异常，请联系管理员!'
					})
				}
			}
		})
	})
	const radioType = ref<number>(0)
	const radio = (type) => {
		radioType.value = type
	}
	const wxLogin = ref<Boolean>(true)
	const wxPhone = ref<Boolean>(false)
	const nameWX = ref<string>()
	const headUrl = ref<string>()
	const loginWx = () => {
		uni.showLoading()
		if (radioType.value == 0) {
			uni.showToast({
				title: '请先同意《用户协议》和《隐私政策》',
				icon: 'none'
			})
			return
		}
		uni.getUserProfile({
			desc: '展示用户信息',
			lang: 'zh_CN',
			success: (file) => {
				const {
					avatarUrl,
					city,
					country,
					gender,
					language,
					nickName,
					province,
				} = JSON.parse(JSON.stringify(file.userInfo))
				headUrl.value = avatarUrl
				console.log(headUrl.value, '微信头像');
				nameWX.value = nickName
				wxlogin()

			}, fail: (err) => {
				// 用户拒绝授权
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}
		})
	}

	const detail = ref<any>(null)
	const openId = ref<any>(null)
	const onGetPhoneNumber = (e) => {
		uni.showLoading()
		// 用户同意授权
		console.log(e, '授权')
		if (e.detail.errMsg == 'getPhoneNumber:ok') {
			detail.value = e.detail;
			uni.showToast({
				title: "授权成功",
				icon: 'none'
			})
			uni.hideLoading()
			Userlogin()
		} else {
			// 用户不同意生效
			console.log('e fail', e);
			uni.showToast({
				title: "授权失败",
				icon: 'none'
			})
			uni.hideLoading()
		}
	}
	const Userlogin = () => {
		let obj = {
			code: detail.value.code,
			openId: openId.value,
			userDoctorId: uni.getStorageSync('sharDoctorId'),
		}
		userLogin(obj).then((res : any) => {
			if (res.code == 200) {
				uni.setStorageSync('tokenName', res.data.tokenName);
				uni.setStorageSync('tokenValue', res.data.tokenValue);
				UserDeatil().then(async (res : any) => {
					if (res.code == 200) {
						uni.setStorageSync('userDoctorId', res.data.id)
						uni.setStorageSync('type', res.data.type)
						uni.setStorageSync('UName', res.data.name)
						uni.setStorageSync('headUrl', res.data.headUrl)
						var tdd = getPolicyBase64();
						var stre = getSignature(tdd);
						let name =
							new Date().getTime() + Math.floor(Math.random() * 150) + "-header.png";
						var aliyunFileKey = "xbl-url/" + name;
						console.log(headUrl.value, '微信头像');
						const { tempFilePath } = await uni.downloadFile({
							url: headUrl.value
						});
						uni.uploadFile({
							url: config.uploadImageUrl,
							filePath: tempFilePath,
							name: "file",
							formData: {
								key: aliyunFileKey,
								policy: tdd,
								OSSAccessKeyId: config.OSSAccessKeyId,
								signature: stre,
								success_action_status: 200,
							},
							success(res2) {
								uni.setStorageSync("headUrl", aliyunFileKey);
								editUserInfo({
									headUrl: aliyunFileKey,
									id: res.data.id,
									name: nameWX.value
								}).then((res3) => {
									uni.switchTab({
										url: '/pages/index/index'
									})
								});
							},
							fail(res4) {
								uni.switchTab({
									url: '/pages/index/index'
								})
								console.log("upload fail", res4);
							},
						});

					}
				}).catch(err => {
					console.log(err)
				})

			}
		})
	}
	const wxlogin = () => {
		let data : any = {
			code: code.value,
		};
		if (detail.value) {
			data.cipherText = detail.value.encryptedData
			data.iv = detail.value.iv
		}
		isWxLogin(data).then((res : any) => {
			if (res.code == 200) {
				uni.hideLoading()
				if (res.data.openId) {
					uni.showToast({
						title: "请授权手机号",
						icon: 'none'
					})
					openId.value = res.data.openId
					wxPhone.value = true
					wxLogin.value = false
				} else {
					uni.setStorageSync('tokenName', res.data.saTokenInfo.tokenName);
					uni.setStorageSync('tokenValue', res.data.saTokenInfo.tokenValue);
					UserDeatil().then((res : any) => {
						if (res.code == 200) {
							uni.setStorageSync('userDoctorId', res.data.id)
							uni.setStorageSync('type', res.data.type)
							uni.setStorageSync('UName', res.data.name)
							uni.setStorageSync('headUrl', res.data.headUrl)
						}
					}).catch(err => {
						console.log(err)
					})
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
			}
		})
	}
</script>

<style lang="scss">
	@import './login.scss';

	.big {
		height: 100rpx;
		align-items: start;
	}
</style>